package com.yd.mvc.baseController.util;

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

/**
 * @author 张广
 * @create 2017-06-26 10:19
 **/
public class InstantiationTracingBeanPostProcessor implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if(event.getApplicationContext().getParent()== null){
            // 需要执行的逻辑代码，当spring容器初始化完成后就会执行该方法。
            System.out.println("================================系统初始化=============================");
            String url=LoadPropertyUrl.getPath()+LongTimeUrl.LONG_TIME_PROPERTIES;
            String version_url=LoadPropertyUrl.getPath()+LongTimeUrl.VERSION_WAR_PROPERTIES;
            System.out.println(version_url);
            try {
                String localInfo="";
                InetAddress address = InetAddress.getLocalHost();
                localInfo=address.getHostName()+address.getHostAddress();
                String pwdStr=MD5Util.EncoderByMd5(localInfo);//获取加密字符串
                String war_version=LongTimeUrl.getVersionWar(version_url);
                System.out.println("local="+war_version);
                if(!(war_version.trim().equals(pwdStr.trim())||war_version.trim().equals("0"))){
                    System.out.println("-----------");
                    System.exit(0);
                }
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                long end=LongTimeUrl.getVersionTime(url);
                if(end<=new Date().getTime()){
                    if(end!=0l){
                        LongTimeUrl.addOrUpdateLong(new Date().getTime()+120*60*1000l,url);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("================================初始化配置成功=============================");
        }
    }

}
